﻿using System;
using System.Runtime.Remoting.Messaging;
using System.Security.Cryptography;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;

namespace Sharp.Platform.Owin
{
    public class SharpUserManager : Microsoft.AspNet.Identity.UserManager<SharpUser, Guid>
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="store"></param>
        public SharpUserManager(SharpUserStore store)
            : base(store)
        {
            PasswordHasher = new OldSystemPasswordHasher();
        }
        public static SharpUserManager Create(IdentityFactoryOptions<SharpUserManager> options, IOwinContext context)
        {
            var manager = new SharpUserManager(new SharpUserStore())
            {
                PasswordValidator = new PasswordValidator
                {
                    RequiredLength = 6,
                    RequireNonLetterOrDigit = true,
                    RequireDigit = true,
                    RequireLowercase = true,
                    RequireUppercase = true,
                },
                UserLockoutEnabledByDefault = true,
                DefaultAccountLockoutTimeSpan = TimeSpan.FromMinutes(5),
                MaxFailedAccessAttemptsBeforeLockout = 5
            };
        
            // 注册双重身份验证提供程序。此应用程序使用手机和电子邮件作为接收用于验证用户的代码的一个步骤
            // 你可以编写自己的提供程序并将其插入到此处。
            manager.RegisterTwoFactorProvider("电话代码", new PhoneNumberTokenProvider<SharpUser,Guid>
            {
                MessageFormat = "你的安全代码是 {0}"
            });
            manager.RegisterTwoFactorProvider("电子邮件代码", new EmailTokenProvider<SharpUser,Guid>
            {
                Subject = "安全代码",
                BodyFormat = "你的安全代码是 {0}"
            });

            var dataProtectionProvider = options.DataProtectionProvider;
            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider<SharpUser,Guid>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return manager;
        }

        #region 获取当前登录的用户


        /// <summary>
        /// 当前登录的用户
        /// </summary>
        public static SharpUser Current
        {
            get
            {
                HttpContext current = HttpContext.Current;
                if (current != null)
                {
                    var returnValue = current.Session["SharpUser"] as SharpUser;
                    if (returnValue == null)
                    {
                        returnValue = CallContext.GetData("SharpUser") as SharpUser;
                        if (returnValue != null)
                        {
                            current.Session["SharpUser"] = returnValue; ;
                        }
                        return returnValue;
                    }
                    return returnValue;
                }

                return CallContext.GetData("SharpUser") as SharpUser;
            }
            set
            {
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.Session["SharpUser"] = value; ;
                }
                else
                {
                    CallContext.SetData("SharpUser", value);
                }
            }
        }
        #endregion

    }

    public class OldSystemPasswordHasher : PasswordHasher
    {

        /// <summary>
        /// 对密码进行Hash加密
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public override string HashPassword(string password)
        { 
            return password.Md5();
        }

        /// <summary>
        /// 重写验证密码的方法
        /// </summary>
        /// <param name="hashedPassword">加密后的密码</param>
        /// <param name="providedPassword">提供的密码</param>
        /// <returns></returns>
        public override PasswordVerificationResult VerifyHashedPassword(string hashedPassword, string providedPassword)
        {
            if (hashedPassword == null)
            {
                return PasswordVerificationResult.Failed;
            }
            if (string.IsNullOrEmpty(providedPassword))
            {
                throw new ArgumentNullException(nameof(providedPassword));
            }
           
            if (hashedPassword.Equals(providedPassword.Md5(), StringComparison.CurrentCultureIgnoreCase))
            {
                return PasswordVerificationResult.Success;
            }
            else
            {
                return PasswordVerificationResult.Failed;
            }
        }
 
    }
}